<template>
  <div class="beam-layout-container">
    <!-- 顶部查询条件 -->
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <!-- 所属桥梁 -->
          <bjSelect
            :allowClear="true"
            :loading="bridgeNameLoading"
            placeholder="请选择所属桥梁"
            :replaceFields="bridgeNameReplaceFields"
            :dataResource="bridgeNameSource"
            v-model="bridgeName"
            @change="conditionChange($event, 'bridgeName')"
          >
          </bjSelect>
          <!-- 幅别 -->
          <bjSelect
            :allowClear="true"
            placeholder="请选择幅别"
            :dataResource="amClassSource"
            v-model="amClass"
            @change="conditionChange($event, 'amClass')"
          >
          </bjSelect>
          <!-- 梁类型 -->
          <bjSelect
            :allowClear="true"
            :loading="beamTypeLoading"
            placeholder="请选择梁类型"
            :replaceFields="beamTypeReplaceFields"
            :dataResource="beamTypeSource"
            v-model="beamType"
            @change="conditionChange($event, 'beamType')"
          >
          </bjSelect>
          <!-- 梁号 -->
          <a-input
            placeholder="请输入梁号"
            v-model="componentParts"
            allowClear
          />
        </template>
        <template slot="operate">
          <a-button type="primary" @click="getData()"> 查询 </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="beam-table-container" v-loading="loading">
      <div class="table-header" header="梁信息配置">
        <div>
          <a-button type="primary" @click="operateData(1)"> 新增 </a-button>
          <a-button class="solid-line" @click="QRCodeDownload()">
            二维码下载
          </a-button>
          <a-button
            class="solid-line"
            :loading="importLoading"
            @click="importTemplate()"
          >
            批量导入
          </a-button>
          <a-button
            class="solid-line"
            :loading="exportLoading"
            @click="exportData()"
          >
            批量导出
          </a-button>
          <a-button
            class="solid-line"
            :loading="downloadLoading"
            @click="downloadTemplate()"
          >
            模板下载
          </a-button>
          <input
            accept=".xls,.xlsx"
            @change="importExcel"
            type="file"
            ref="upload"
            id="upload"
            style="display: none"
          />
        </div>
      </div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="99%"
          class="scrollbarStyle"
          align="center"
          show-overflow
          show-header-overflow
          :data="tableData"
          @checkbox-all="onSelectAll"
          @checkbox-change="onSelect"
          :column-config="{ resizable: true }"
        >
          <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column
            show-overflow
            :key="index"
            :title="item.title"
            :field="item.key"
            :width="item.width"
            v-for="(item, index) in columns"
          >
            <template #default="{ row }">
              <div v-if="item.key == 'unionSpan'">
                {{ row.unite || "--" }}联 {{ row.span || "--" }}跨
              </div>
              <div
                v-else-if="item.key == 'rectifyDate'"
                style="position: relative"
              >
                <img
                  @click="viewQrCode(row)"
                  class="code-img"
                  src="https://jszhgd.cn/static/pc/codeIcon.png"
                />
                <div class="code-download">
                  <vue-qr
                    :id="'qr' + row.id"
                    :text="row.qrCodePath"
                    :margin="0"
                    :size="300"
                    :autoColor="true"
                    :logoSrc="logo"
                    :logoScale="0.2"
                  >
                  </vue-qr>
                </div>
              </div>
              <div v-else>{{ row[item.key] }}</div>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            width="220"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  type="link"
                  v-if="row.view"
                  @click="operateData(2, row)"
                >
                  查看
                </a-button>
                <a-button
                  type="link"
                  @click="operateData(3, row)"
                  v-if="row.editAll || row.editPart"
                >
                  编辑
                </a-button>
                <a-button
                  type="link"
                  class="danger"
                  v-if="row.del"
                  @click="handleDelClick(row)"
                >
                  删除
                </a-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="pager-container">
        <vxe-pager
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump']"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              第<span>1</span>到<span
                >{{ Math.ceil(pager.total / pager.pageSize) || 1 }}页 </span
              >共<span>{{ pager.total }}</span
              >条记录
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 操作页面 -->
    <operatePage
      :visible.sync="operatePageVisible"
      :type="operateType"
      :row="row"
    ></operatePage>
    <!-- 二维码信息弹窗 -->
    <qrCodeModal :visible.sync="qrCodeVisible" :dataSource="row"></qrCodeModal>
  </div>
</template>

<script>
import vueQr from "vue-qr";
import JSZip from "jszip";
import html2canvas from "html2canvas";
import { saveAs } from "file-saver";
import bjSelect from "@/components/bj-select";
import operatePage from "./views/operate.vue";
import qrCodeModal from "./components/qrCodeModal.vue";
import {
  downLoadFileByArraybuffer,
  getNowDateStr,
  notificationTip,
  chartString,
} from "@/utils";
import { getLoginData } from "@/tools";
import { getDickeyList } from "@/api/common";
import {
  getBridgeList,
  getList,
  deleteData,
  exportData,
  importExcel,
  downloadMaterialInTemplate,
} from "@/api/wisdom-beam/beamInfoConfig";

export default {
  components: {
    bjSelect,
    operatePage,
    vueQr,
    qrCodeModal,
  },
  data() {
    return {
      row: {},
      importLoading: false,
      exportLoading: false,
      downloadLoading: false,
      operatePageVisible: false,
      operateType: 1,
      //梁号
      componentParts: "",
      //所属桥梁
      bridgeName: undefined,
      bridgeNameSource: [],
      bridgeNameLoading: false,
      bridgeNameReplaceFields: { key: "key", label: "value" },
      //所属幅别
      amClass: undefined,
      amClassSource: [
        {
          key: "左幅",
          value: "左幅",
        },
        {
          key: "右幅",
          value: "右幅",
        },
      ],
      //所属梁类型
      beamTypeLoading: false,
      beamType: undefined,
      beamTypeSource: [],
      beamTypeReplaceFields: { key: "dicValue", label: "dicDesc" },
      columns: [
        {
          title: "梁号",
          key: "componentParts",
        },
        {
          title: "所属桥梁",
          key: "bridgeName",
        },
        {
          title: "一联一跨",
          key: "unionSpan",
        },
        {
          title: "幅别",
          key: "amClass",
        },
        {
          title: "长度（m）",
          key: "beamLength",
        },
        {
          title: "梁类型",
          key: "beamTypeDesc",
        },
        {
          title: "强度等级",
          key: "strengthGradeDesc",
        },
        {
          title: "设计方量（m³）",
          key: "designVolume",
        },
        {
          title: "二维码",
          key: "rectifyDate",
          fixed: "right",
          width: 120,
        },
      ],
      tableData: [],
      loading: false,
      pager: {
        page: 1,
        pageSize: 10,
        total: 0,
      },
      //二维码
      choosedTableList: [],
      logo: "https://jszhgd.cn/static/pc/beamyard/qr_icon.jpg",
      //二维码信息弹窗
      qrCodeVisible: false,
    };
  },
  mounted() {
    this.getBridgeList();
    this.getBeamType();
    this.getData();
  },
  methods: {
    //二维码预览
    viewQrCode(item = {}) {
      this.row = item;
      this.qrCodeVisible = true;
    },

    //二维码下载
    QRCodeDownload() {
      let { choosedTableList } = this;
      if (choosedTableList.length == 0) {
        this.$message.warning("请选择您要下载的二维码！");
        return;
      }
      if (choosedTableList.length == 1) {
        let row = choosedTableList?.[0] ?? {};
        this.downloadQrCode(row);
      } else {
        this.downloadQrCodes(choosedTableList);
      }
    },

    //二维码-单张下载-图片
    async downloadQrCode(row = {}) {
      var htmlName = document.getElementById("qr" + row.id);
      const canvas = await html2canvas(htmlName);
      const dataUrl = canvas.toDataURL("image/png");
      const blob = await fetch(dataUrl).then((res) => res.blob());
      saveAs(blob, `${row.bridgeName}-${row.beamlocation}.png`);
    },

    //二维码-批量下载-压缩包
    async downloadQrCodes(data = []) {
      const zip = new JSZip();
      // 循环生成二维码并添加到压缩包;
      for (let i = 0; i < data.length; i++) {
        const row = data[i];
        var htmlName = document.getElementById("qr" + row.id);
        const canvas = await html2canvas(htmlName);
        const dataUrl = canvas.toDataURL("image/png");
        const blob = await fetch(dataUrl).then((res) => res.blob());
        zip.file(`${row.bridgeName}-${row.beamlocation}.png`, blob);
      }
      // 生成压缩包并下载
      zip.generateAsync({ type: "blob" }).then((content) => {
        saveAs(content, "梁信息配置.zip");
      });
    },

    onSelectAll() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords();
      this.choosedTableList = selectRecords;
    },

    onSelect() {
      let selectRecords = this.$refs.xTable.getCheckboxRecords();
      this.choosedTableList = selectRecords;
    },

    //查询桥梁列表
    getBridgeList() {
      this.bridgeNameLoading = true;
      return new Promise((resolve, reject) => {
        getBridgeList({})
          .then((res) => {
            let { data } = res;
            let list = data?.result || [];
            this.bridgeNameSource = list.map((v) => {
              return { key: v, value: v };
            });
            resolve();
          })
          .catch((_) => {
            this.bridgeNameSource = [];
            reject();
          })
          .finally((_) => {
            this.bridgeNameLoading = false;
          });
      });
    },

    //查询梁类型
    getBeamType() {
      this.beamTypeLoading = true;
      return new Promise((resolve, reject) => {
        getDickeyList({ dictKey: "TASK_MANAGER_TYPE" })
          .then((res) => {
            let { data } = res;
            this.beamTypeSource = data?.result ?? [];
            resolve();
          })
          .catch((_) => {
            this.beamTypeSource = [];
            reject();
          })
          .finally((_) => {
            this.beamTypeLoading = false;
          });
      });
    },

    //查询列表
    getData() {
      this.choosedTableList = [];
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { page, pageSize } = this.pager;
        let { componentParts, bridgeName, amClass, beamType } = this;
        let { tenantCode, userId, sysSource } = getLoginData();
        getList({
          page,
          pageSize,
          componentParts: componentParts || "",
          bridgeName: bridgeName?.key || "",
          amClass: amClass?.key || "",
          beamType: beamType?.key,
        })
          .then((res) => {
            let { data } = res;
            this.tableData = data?.result?.rows ?? [];
            this.pager.total = data?.result?.total ?? 0;
            this.tableData.forEach((item) => {
              let { qrCode } = item;
              let qrUrl =
                `http://lh.gzbsx.com:70/dashboard/h5/qr.html` +
                chartString({
                  qrCode,
                });
              this.$set(item, "qrCodePath", qrUrl);
            });
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听筛选条件切换
    conditionChange(ev, keyName) {
      this[keyName] = ev;
      this.getData();
    },

    // 导入
    importTemplate() {
      this.$refs.upload.click();
    },

    importExcel(event) {
      let files = event.target.files;
      let formdata = new FormData();
      for (let i = 0; i < files.length; i++) {
        formdata.append("imfile", files[i]);
      }
      this.importLoading = true;
      importExcel(formdata)
        .then((res) => {
          event.target.value = "";
          if (res.data.result.errorMsg.length == 0) {
            notificationTip("success", "梁信息导入成功");
            this.getData();
          } else {
            let msg = res.data.result.errorMsg.join("");
            notificationTip("error", msg, "提示", 2);
          }
        })
        .catch((err) => {
          event.target.value = "";
        })
        .finally((_) => {
          this.importLoading = false;
        });
    },

    //批量导出
    exportData() {
      let { componentParts, bridgeName, amClass, beamType } = this;
      this.exportLoading = true;
      exportData({
        componentParts: componentParts || "",
        bridgeName: bridgeName?.key || "",
        amClass: amClass?.key || "",
        beamType: beamType?.key,
      })
        .then((data) => {
          downLoadFileByArraybuffer(data, "梁信息配置" + getNowDateStr());
        })
        .finally((_) => {
          this.exportLoading = false;
        });
    },

    //模板下载
    downloadTemplate() {
      this.downloadLoading = true;
      downloadMaterialInTemplate({})
        .then((data) => {
          downLoadFileByArraybuffer(data, "梁信息配置模板" + getNowDateStr());
        })
        .finally((_) => {
          this.downloadLoading = false;
        });
    },

    //跳转操作页面
    operateData(type = 1, row = {}) {
      this.operateType = type;
      this.row = row;
      this.operatePageVisible = true;
    },

    //删除
    handleDelClick(row) {
      let that = this;
      let dataLength = that.tableData.length;
      let { id } = row;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定删除所选内容?",
        content: "删除内容后,将无法恢复。",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FB5A5A",
          }),
        onOk() {
          deleteData({ id })
            .then((res) => {
              if (dataLength == 1 && that.pager.page > 1) {
                that.pager.page -= 1;
              }
              notificationTip("success", "删除成功！");
              that.getData();
            })
            .catch();
        },
        onCancel() {},
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.choosedTableList = [];
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getData();
    },
  },
};
</script>

<style lang="less" scoped>
.code-img {
  width: 30px;
  height: 30px;
  margin: 0 auto;
  cursor: pointer;
}
.code-download {
  width: 300px;
  height: 300px;
  position: absolute;
  opacity: 0;
}
</style>
